package spring.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import spring.annotation.MetricTime;

@Aspect
@Component
public class MetricAspect {

    @Pointcut(value = "@annotation(spring.annotation.MetricTime)")
    public void pointCut() {}

    @Around("pointCut() && @annotation(mt)")
    public Object metric(ProceedingJoinPoint pj, MetricTime mt) throws Throwable {
        String value = mt.value();
        long start = System.currentTimeMillis();
        try {
            return pj.proceed();
        } finally {
            long cos = System.currentTimeMillis() - start;
            System.out.printf("[Metric(%s)]: %d ms%n", value, cos);
        }
    }
}
